use std::str::FromStr;

// 将任意进制的数字字符串转换为十进制数
fn to_decimal(num: &str, base: u32) -> u32 {
    let mut result = 0;
    let mut power = 1;
    for ch in num.chars().rev() {
        let digit = ch.to_digit(base).expect("Invalid character for the base");
        result += digit * power;
        power *= base;
    }
    result
}

// 将十进制数转换为任意进制的数字字符串
fn from_decimal(num: u32, base: u32) -> String {
    if num == 0 {
        return "0".to_string();
    }

    let mut result = String::new();
    let mut n = num;
    while n > 0 {
        let remainder = n % base;
        result.push(char::from_digit(remainder, base).expect("Invalid digit"));
        n /= base;
    }
    
    result.chars().rev().collect()
}

// 任意进制之间的转换函数
pub fn convert_base(num_str: &str, to_base: u32) -> String {
    // 解析源进制和数字
    let parts: Vec<&str> = num_str.split('(').collect();
    if parts.len() != 2 {
        return "Invalid input format".to_string();
    }

    let number = parts[0].trim();
    let base_str = parts[1].trim_end_matches(')');
    
    let from_base = u32::from_str(base_str).unwrap_or(10); // 默认进制为10

    // 将源进制的数字转换为十进制
    let decimal = to_decimal(number, from_base);

    // 将十进制数转换为目标进制的数字字符串
    from_decimal(decimal, to_base)
}